﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using clf.weighing.entity;
using MyHelper;
using HandyControl.Controls;
using TextBox = System.Windows.Controls.TextBox;
using System.Windows.Input;
using System.Windows.Media;
using UserControl = System.Windows.Controls.UserControl;
using Point = System.Windows.Point;
using ComboBox = System.Windows.Controls.ComboBox;

namespace weighing
{

    /// <summary>
    /// 过磅操作用户界面的公共类
    /// 
    ///TODO 手动过磅时，不支持判断 是否指定磅房过磅
    /// </summary>
    public abstract class WeighingUserContent : UserControl
    {

        #region variables
        protected WeighingBill? mWeighingBill;
        //当前的磅单编号
        protected String currBillNumber;

        //当前的磅单类型出库 
        protected WeightingBillType currBillType;
        //是否出场
        protected bool isOutFactory = false;
        protected CompanyVo? sendCompanyVo;
        protected CompanyVo? receiverCompanyVo;
        protected CompanyVo? tranceCompanyVo;
        protected MaterialVo? currMaterialVo;
        protected CarInfoVo? currCarVo;
        /// <summary>
        /// 是否为设置控件的值，默认 false
        /// </summary>
        protected bool isBindingValue = false;
        /// <summary>
        /// 当前 默认 或者选中的 磅称仪表
        /// </summary>
        public ScaleItem? ActiveScaleItem;

        protected ObservableCollection<YardVo> ShareYrardVos = new ObservableCollection<YardVo>();
        protected ObservableCollection<YardVo> SendCompanyYrardVos = new ObservableCollection<YardVo>();
        protected ObservableCollection<YardVo> ReceiveCompanyYrardVos = new ObservableCollection<YardVo>();
        #endregion

        #region property
        /// <summary>
        /// 是否是车牌号识别成功后过磅
        /// </summary>
        public bool IsRecongnizePlateWeighing { get; set; } = false;

        public bool IsInsert { get; set; } = true;
        #endregion


        #region abstract
        public abstract void OnDefaultScaleHouseChanged(ScaleHouseVo vo);

        public abstract void OnBillSettingChanged();

        public abstract void OnIgnoreTraeChanged();

        public abstract void OnBackupBillFieldChangedHandle(BackupBillField backupBillField);

        public abstract Canvas GetCanvas();
        #endregion

        /// <summary>
        /// 发货公司和客户是不能是同一个公司
        /// </summary>
        /// <returns></returns>
        protected bool CheckSupplyCustomer(WeightingBillType type)
        {
            if (type == WeightingBillType.Buy)
            {
                if (App.Config.WeighingConfig.InNotSameCompany == false) { return true; }
            }
            else if (type == WeightingBillType.Sale)
            {
                if (App.Config.WeighingConfig.OutNotSameCompany == false) { return true; }
            }

            if (receiverCompanyVo != null && sendCompanyVo != null)
            {
                if (receiverCompanyVo.Id == sendCompanyVo.Id)
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 数据控件和称重控件在一起时，过磅成功，需要刷新。
        /// </summary>
        protected void DataUcLoadData(WeightingBillType type)
        {
            StackPanel? parent = this.Parent as StackPanel;
            if (parent != null && parent.Children.Count == 2)
            {
                if (type == WeightingBillType.Buy)
                {
                    InputDataContent dataUc = parent?.Children[1] as InputDataContent;
                    if (dataUc != null)
                    {
                        dataUc.LoadData();
                    }
                }
                else
                {
                    OutputDataContent dataUc = parent?.Children[1] as OutputDataContent;
                    if (dataUc != null)
                    {
                        dataUc.LoadData();
                    }
                }

            }
        }

        protected void UpdateUsedBaseDataThread()
        {
            // success to do TempUpdateUsedBase
            //Thread thread = new Thread(new ParameterizedThreadStart(CommonFunction.TempUpdateUsedBase));
            //thread.Start(new BaseDataClassV() { Send = sendCompanyVo, Receive = receiverCompanyVo, Material = currMaterialVo, CarInfo = currCarVo });


            //update backup field itemsource
            var cbs = this.GetCanvas().Children.OfType<ComboBox>().ToList();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var b in cbs)
            {
                if (!string.IsNullOrEmpty(b.Text))
                {
                    dic?.Add(b.Name, b.Text);
                }              
            }
            _ = UpdateBackupFieldComboBoxItemSourceAsync(dic);

            AddBackupFiledItemSource();

        }

        protected void SaveRemark(ComboBox remarkCb, string remark,bool isInput = false)
        {
            if (remark.IsNullOrEmpty()) return;
            string key = isInput? "InputReamak" : "OutputReamak";
            var itemsource = GlobalData.GetAllItemSource();
            var ris = itemsource != null ? (itemsource.Keys.Contains(key) ? itemsource[key] : null) : null;
            if (ris != null)
            {
                if (!ris.Contains(remark))
                {
                    ris.Add(remark);
                    itemsource[key] = ris;
                }
            }
            else
            {
                ris = new List<string> { remark };
                if (itemsource.Keys.Contains(key))
                {
                    itemsource[key] = ris;
                }
                else
                {
                    itemsource.Add(key, ris);
                }
            }
            remarkCb.ItemsSource = null;
            remarkCb.ItemsSource = ris;
        }


        #region 模拟数据

        protected DispatcherTimer moniDispatcherTimer;

        protected void StartMoniTimer(WeightingBillType type)
        {
            if (moniDispatcherTimer == null)
            {
                moniDispatcherTimer = new DispatcherTimer();
                moniDispatcherTimer.Tick += (sender, args) =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        double tonner;
                        bool isOut = false;
                        if (type == WeightingBillType.Buy)
                        {
                            isOut = App.Config.WeighingConfig.Times == 1 ? false : isOutFactory;
                        }
                        else if (type == WeightingBillType.Sale)
                        {
                            isOut = App.Config.WeighingConfig.OutTimes == 1 ? false : isOutFactory;
                        }
                        tonner = CommonFunction.RandomTonner(currBillType, isOut);
                        CommonFunction.SetTonner(tonner);
                    });
                };
                moniDispatcherTimer.Interval = TimeSpan.FromSeconds(1.1);
            }
            moniDispatcherTimer.Start();
        }

        protected void StopMoniTimer()
        {
            moniDispatcherTimer?.Stop();
        }

        #endregion


        /// <summary>
        /// 内部车检查
        /// </summary>
        /// <param name="carInfo"></param>
        /// <returns></returns>
        protected bool CheckSelfCar(CarInfo carInfo)
        {
            if (App.Config.WeighingConfig.CarLimit == 1)
            {
                if (carInfo == null || carInfo.isSelf == 0)
                {
                    return false;
                }
            }
            return true;
        }




        protected void RegistryDelegete()
        {
            DelegeteFactory.Instance.OnWeighingConfigChanged += OnWeighingConfigChanged;
            DelegeteFactory.Instance.OnYardAdd += OnYardAdd;
            DelegeteFactory.Instance.OnYardUpdate += OnYardUpdate;
            DelegeteFactory.Instance.OnDefaultScaleHouseChanged += OnDefaultScaleHouseChanged;
            DelegeteFactory.Instance.OnBillSettingChanged += OnBillSettingChanged;

            DelegeteFactory.Instance.OnBackupBillFieldChanged += OnBackupBillFieldChangedHandle;
        }


        protected void ClearDelegete()
        {
            try
            {
                DelegeteFactory.Instance.OnWeighingConfigChanged -= OnWeighingConfigChanged;
                DelegeteFactory.Instance.OnYardAdd -= OnYardAdd;
                DelegeteFactory.Instance.OnYardUpdate -= OnYardUpdate;
                DelegeteFactory.Instance.OnDefaultScaleHouseChanged -= OnDefaultScaleHouseChanged;
                DelegeteFactory.Instance.OnBillSettingChanged -= OnBillSettingChanged;

                DelegeteFactory.Instance.OnBackupBillFieldChanged += OnBackupBillFieldChangedHandle;
            }
            catch (Exception ex)
            {
                Log.Error("WeighingUserContent ->ClearDelegete:" + ex.Message);
            }
        }


        #region OnWeighingConfigChanged
        private void OnWeighingConfigChanged(WeighingConfig WeighingConfig)
        {
            OnIgnoreTraeChanged();
        }

        private void OnYardAdd(Yard yard)
        {
            if (yard == null) return;
            if (App.Config.WeighingConfig.YardUseType == YardUserType.Share)
            {
                ShareYrardVos.Add(new YardVo(yard));
            }
            else
            {
                if (sendCompanyVo != null && sendCompanyVo.Id == yard.companyId)
                {
                    SendCompanyYrardVos.Add(new YardVo(yard));
                }
                else if (receiverCompanyVo != null && receiverCompanyVo.Id == yard.companyId)
                {
                    ReceiveCompanyYrardVos.Add(new YardVo(yard));
                }
            }
        }

        private void OnYardUpdate(Yard yard)
        {
            if (App.Config.WeighingConfig.YardUseType == YardUserType.Share)
            {

                YardVo old = null;
                foreach (var item in ShareYrardVos)
                {
                    if (item.Id == yard.id)
                    {
                        old = item;
                        break;
                    }
                }
                if (old != null && old.Name != yard.name)
                {
                    old.Name = yard.name;
                }
            }
        }
        #endregion

        protected string GetWeighingNumber()
        {
            //不自动生成返回空
            if (App.Config.BillPrintConfig.AutoGeneretor == false)
            {
                return "";
            }
            return BillNumberHelper.GetWeighingNumber(currBillType);
        }

        #region backup field

        /// <summary>
        /// 添加备用字段控件
        /// </summary>
        /// <param name="canvas">布局 Canvas</param>
        protected void AddBackFieldControl(Canvas canvas)
        {
            int type = (int)currBillType;

            List<BackupBillField> fields = BackupBillFieldDao.Instance.SelectAllByType(type);

            if (fields == null || fields.Count == 0) return;

            foreach (var field in fields)
            {
                if (field.isEnable == 1)
                {
                    if (field.controlType == (int)BackFieldControlType.Combox)
                    {
                        var combox = CreateComboBox(field);
                        canvas.Children.Add(combox);

                        //set combobox back bil feild item source
                        SetComboBoxBackupFieldItemSource(combox);
                    }
                    else
                    {
                        var textBox = CreateTextBox(field);
                        canvas.Children.Add(textBox);
                    }
                }
            }
        }


        /// <summary>
        /// 获取备用字段的值
        /// </summary>
        protected bool GetBackFieldValue(Canvas canvas)
        {
            if (mWeighingBill == null) return false;

            List<TextBox> tbs = new List<TextBox>();
            List<ComboBox> cbs = new List<ComboBox>();
            var childs = canvas.Children;
            for (int i = 0; i < childs.Count; i++)
            {
                if (childs[i] is TextBox box)
                {
                    //名称与 backup 开头的，TextBox 才是备用字段
                    if (box.Name.StartsWith("backup")) tbs.Add(box);
                }
                else if (childs[i] is ComboBox cb)
                {
                    //名称与 backup 开头的，TextBox 才是备用字段
                    if (cb.Name.StartsWith("backup")) cbs.Add(cb);
                }
            }

            for (int i = 0; i < tbs.Count; i++)
            {
                try
                {
                    var tb = tbs[i];
                    if (tb != null)
                    {
                        var name = tb.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            mWeighingBill.backupString1 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            mWeighingBill.backupString2 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            mWeighingBill.backupString3 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            mWeighingBill.backupString4 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            mWeighingBill.backupString5 = tb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {

                            mWeighingBill.backupInt1 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {

                            mWeighingBill.backupInt2 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {

                            mWeighingBill.backupInt3 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {

                            mWeighingBill.backupInt4 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            mWeighingBill.backupInt5 = Convert.ToInt32(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            mWeighingBill.backupDecimal1 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            mWeighingBill.backupDecimal2 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            mWeighingBill.backupDecimal3 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            mWeighingBill.backupDecimal4 = Convert.ToDecimal(tb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            mWeighingBill.backupDecimal5 = Convert.ToDecimal(tb.Text.Trim());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("备用字段输入有错：" + ex.Message, "main");
                    return false;
                }
            }


            for (int i = 0; i < cbs.Count; i++)
            {
                try
                {
                    var cb = cbs[i];
                    if (cb != null)
                    {
                        var name = cb.Name.Replace("CB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            mWeighingBill.backupString1 = cb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            mWeighingBill.backupString2 = cb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            mWeighingBill.backupString3 = cb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            mWeighingBill.backupString4 = cb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            mWeighingBill.backupString5 = cb.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {
                            mWeighingBill.backupInt1 = Convert.ToInt32(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {
                            mWeighingBill.backupInt2 = Convert.ToInt32(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {
                            mWeighingBill.backupInt3 = Convert.ToInt32(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {
                            mWeighingBill.backupInt4 = Convert.ToInt32(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            mWeighingBill.backupInt5 = Convert.ToInt32(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            mWeighingBill.backupDecimal1 = Convert.ToDecimal(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            mWeighingBill.backupDecimal2 = Convert.ToDecimal(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            mWeighingBill.backupDecimal3 = Convert.ToDecimal(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            mWeighingBill.backupDecimal4 = Convert.ToDecimal(cb.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            mWeighingBill.backupDecimal5 = Convert.ToDecimal(cb.Text.Trim());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("备用字段输入有错：" + ex.Message, "main");
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 更新UI
        /// </summary>
        /// <param name="field"></param>
        /// <param name="canvas"></param>

        protected void UpdateBackFieldTextBox(BackupBillField field, Canvas canvas)
        {
            string name = field.controlType == (int)BackFieldControlType.Combox ? (field.fiedName + "CB") : (field.fiedName + "TB");
            if (field.isEnable == 1)
            {
                if (field.controlType == (int)BackFieldControlType.Combox)
                {
                    //if not exist ,add 
                    ComboBox? comboBox = FindControl<ComboBox>(name, canvas);

                    if (comboBox == null)
                    {
                        comboBox = CreateComboBox(field);
                        canvas.Children.Add(comboBox);
                    }
                    else
                    {
                        // exist update
                        InfoElement.SetTitle(comboBox, field.displayName);
                        //InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
                        InfoElement.SetTitleWidth(comboBox, new GridLength(Convert.ToDouble(field.titleWidth)));
                        Canvas.SetLeft(comboBox, field.left);
                        Canvas.SetTop(comboBox, field.top);
                        comboBox.Width = field.width;
                    }
                }
                else
                {
                    //if not exist ,add 
                    TextBox? textBox = FindControl<TextBox>(name, canvas);
                    if (textBox == null)
                    {
                        textBox = CreateTextBox(field);
                        canvas.Children.Add(textBox);
                    }
                    else
                    {
                        // exist update
                        InfoElement.SetTitle(textBox, field.displayName);
                        //InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
                        InfoElement.SetTitleWidth(textBox, new GridLength(Convert.ToDouble(field.titleWidth)));
                        Canvas.SetLeft(textBox, field.left);
                        Canvas.SetTop(textBox, field.top);
                        textBox.Width = field.width;
                    }
                }
            }
            else
            {
                if (field.controlType == (int)BackFieldControlType.Combox)
                {
                    ComboBox? comboBox = FindControl<ComboBox>(name, canvas);

                    if (comboBox != null)
                    {
                        //exist ,delete 
                        canvas.Children.Remove(comboBox);
                    }
                }
                else
                {
                    TextBox? textBox = FindControl<TextBox>(name, canvas);
                    if (textBox != null)
                    {
                        //exist ,delete 
                        canvas.Children.Remove(textBox);
                    }
                }
            }
        }

        protected TextBox FindTextBox(string name, Canvas canvas)
        {
            var childs = canvas.Children;
            foreach (var item in childs)
            {
                if (item is TextBox tb)
                {
                    if (tb.Name.Equals(name))
                        return tb;
                }
            }
            return null;
        }


        protected T? FindControl<T>(string name, Canvas canvas) where T : System.Windows.Controls.Control
        {
            var childs = canvas.Children;
            foreach (var item in childs)
            {
                if (item is T control)
                {
                    if (control.Name.Equals(name))
                        return control;
                }
            }
            return null;
        }

        protected TextBox CreateTextBox(BackupBillField field)
        {
            int w = field.width < 200 ? 200 : field.width;
            w = field.width > 400 ? 400 : field.width;
            var textBox = new TextBox()
            {
                Name = field.fiedName + "TB",
                Style = App.Current.FindResource("TextBoxExtend") as Style,
                Margin = new Thickness(5, 2, 5, 2),
                MinWidth = 100,
                MaxWidth = 400,
                Width = w,
                ToolTip = $"备用字段：{field.displayName}",
                FontSize = 14
            };
            InputScope scope = new InputScope();
            if (!field.fiedName.Contains("string"))
            {
                InputScopeName name = new InputScopeName
                {
                    NameValue = InputScopeNameValue.Number
                };
                scope.Names.Add(name);
                textBox.InputScope = scope;
            }
            InfoElement.SetTitle(textBox, field.displayName);
            InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
            InfoElement.SetTitleWidth(textBox, new GridLength(Convert.ToDouble(field.titleWidth)));
            Canvas.SetLeft(textBox, field.left);
            Canvas.SetTop(textBox, field.top);
            //drag event
            textBox.MouseLeftButtonDown += TextBox_MouseLeftButtonDown;
            textBox.MouseLeftButtonUp += TextBox_MouseLeftButtonUp;
            textBox.MouseMove += TextBox_MouseMove;
            return textBox;
        }


        protected ComboBox CreateComboBox(BackupBillField field)
        {
            int w = field.width < 200 ? 200 : field.width;
            w = field.width > 400 ? 400 : field.width;
            var comboBox = new ComboBox()
            {
                Name = field.fiedName + "CB",
                Style = App.Current.FindResource("ComboBoxExtend") as Style,
                Margin = new Thickness(5, 2, 5, 2),
                MinWidth = 100,
                MaxWidth = 400,
                MaxDropDownHeight = 300,
                Width = w,
                IsEditable = true,
                ToolTip = $"备用字段：{field.displayName}",
                FontSize = 14
            };
            InputScope scope = new InputScope();
            if (!field.fiedName.Contains("string"))
            {
                InputScopeName name = new InputScopeName
                {
                    NameValue = InputScopeNameValue.Number
                };
                scope.Names.Add(name);
                comboBox.InputScope = scope;
            }
            InfoElement.SetTitle(comboBox, field.displayName);
            InfoElement.SetTitlePlacement(comboBox, HandyControl.Data.TitlePlacementType.Left);
            InfoElement.SetTitleWidth(comboBox, new GridLength(Convert.ToDouble(field.titleWidth)));
            Canvas.SetLeft(comboBox, field.left);
            Canvas.SetTop(comboBox, field.top);
            //drag event
            comboBox.MouseLeftButtonDown += TextBox_MouseLeftButtonDown;
            comboBox.MouseLeftButtonUp += TextBox_MouseLeftButtonUp;
            comboBox.MouseMove += TextBox_MouseMove;
            return comboBox;
        }

        protected void ClearBackFieldValue()
        {
            var canvas = GetCanvas();
            if (canvas == null) return;
            var chilreds = canvas.Children;
            for (int i = 0; i < chilreds.Count; i++)
            {
                var child = chilreds[i];

                if (child is TextBox)
                {
                    var tb = child as TextBox;
                    if (tb != null && tb.Name.Contains("backup"))
                    {
                        tb.Text = String.Empty;
                    }
                }
                else
                {
                    if (child is ComboBox cb && cb.Name.Contains("backup"))
                    {
                        cb.Text = String.Empty;
                        cb.SelectedIndex = -1;
                    }
                }
            }
        }

        protected void SetterBackFieldValue(WeighingBill bill)
        {
            var canvas =GetCanvas();
            if (bill == null || canvas == null) return;
            var chilreds = canvas.Children;
            for (int i = 0; i < chilreds.Count; i++)
            {
                var child = chilreds[i];

                if (child is TextBox tb)
                {
                    if (tb == null) continue;
                    string name = tb.Name.Replace("TB", "");
                    //可以将 WeighingBill 转换成   Dictionary<string,string> ,就可以不用写这么多的 分支
                    if (name.Equals(Constant.BackfieldName.BackString1))
                    {
                        tb.Text = bill.backupString1;
                    }
                    else if (name.Equals(Constant.BackfieldName.BackString2))
                    {
                        tb.Text = bill.backupString2;
                    }
                    else if (name.Equals(Constant.BackfieldName.BackString3))
                    {
                        tb.Text = bill.backupString3;
                    }
                    else if (name.Equals(Constant.BackfieldName.BackString4))
                    {
                        tb.Text = bill.backupString4;
                    }
                    else if (name.Equals(Constant.BackfieldName.BackString5))
                    {
                        tb.Text = bill.backupString5;
                    }
                    else if (name.Equals(Constant.BackfieldName.BackInt1))
                    {
                        tb.Text = bill.backupInt1.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackInt2))
                    {
                        tb.Text = bill.backupInt2.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackInt3))
                    {
                        tb.Text = bill.backupInt3.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackInt4))
                    {
                        tb.Text = bill.backupInt4.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackInt5))
                    {
                        tb.Text = bill.backupInt5.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackDecimal1))
                    {
                        tb.Text = bill.backupDecimal1.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackDecimal2))
                    {
                        tb.Text = bill.backupDecimal2.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackDecimal3))
                    {
                        tb.Text = bill.backupDecimal3.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackDecimal4))
                    {
                        tb.Text = bill.backupDecimal4.ToString();
                    }
                    else if (name.Equals(Constant.BackfieldName.BackDecimal5))
                    {
                        tb.Text = bill.backupDecimal5.ToString();
                    }
                    else
                    {
                        tb.Text = string.Empty;
                    }
                }
                else
                {
                    if (child is ComboBox cb)
                    {
                        if (cb == null) continue;
                        string name = cb.Name.Replace("CB", "");
                        //可以将 WeighingBill 转换成   Dictionary<string,string> ,就可以不用写这么多的 分支
                        if (name.Equals(Constant.BackfieldName.BackString1))
                        {
                            cb.Text = bill.backupString1;
                        }
                        else if (name.Equals(Constant.BackfieldName.BackString2))
                        {
                            cb.Text = bill.backupString2;
                        }
                        else if (name.Equals(Constant.BackfieldName.BackString3))
                        {
                            cb.Text = bill.backupString3;
                        }
                        else if (name.Equals(Constant.BackfieldName.BackString4))
                        {
                            cb.Text = bill.backupString4;
                        }
                        else if (name.Equals(Constant.BackfieldName.BackString5))
                        {
                            cb.Text = bill.backupString5;
                        }
                        else if (name.Equals(Constant.BackfieldName.BackInt1))
                        {
                            cb.Text = bill.backupInt1.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackInt2))
                        {
                            cb.Text = bill.backupInt2.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackInt3))
                        {
                            cb.Text = bill.backupInt3.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackInt4))
                        {
                            cb.Text = bill.backupInt4.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackInt5))
                        {
                            cb.Text = bill.backupInt5.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackDecimal1))
                        {
                            cb.Text = bill.backupDecimal1.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackDecimal2))
                        {
                            cb.Text = bill.backupDecimal2.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackDecimal3))
                        {
                            cb.Text = bill.backupDecimal3.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackDecimal4))
                        {
                            cb.Text = bill.backupDecimal4.ToString();
                        }
                        else if (name.Equals(Constant.BackfieldName.BackDecimal5))
                        {
                            cb.Text = bill.backupDecimal5.ToString();
                        }
                        else
                        {
                            cb.Text = string.Empty;
                        }
                    }
                }
            }
        }

        protected async Task<bool> UpdateBackupFieldComboBoxItemSourceAsync(Dictionary<string, string> dic)
        {
            return await Task<bool>.Factory.StartNew(() =>
            {
                var itemSource = GlobalData.GetAllItemSource();
                itemSource ??= new Dictionary<string, List<string>>();
                foreach (var kv in dic)
                {
                    if (itemSource.Keys.Contains(kv.Key))
                    {
                        var list = itemSource[kv.Key];
                        if (!list.Contains(kv.Value))
                        {
                            list.Add(kv.Value);
                            itemSource[kv.Key] = list;
                        }
                    }
                    else
                    {
                        itemSource.Add(kv.Key, new List<string>() { kv.Value });
                    }
                }

                //update
                if (itemSource != null && itemSource.Count > 0)
                {
                    BackupItemsHelper.Instance.UpdateToFile(itemSource);
                }

                return true;
            });
        }


        protected void AddBackupFiledItemSource()
        {
            //update combox dispacher to main thread
            var cbs = GetCanvas().Children.OfType<ComboBox>().ToList();
            if (cbs == null || cbs.Count == 0) return;
            foreach (var cb in cbs)
            {
                SetComboBoxBackupFieldItemSource(cb);
            }
        }

        /// <summary>
        /// Set ComboBox ItemSource
        /// </summary>
        /// <param name="cb"></param>
        protected void SetComboBoxBackupFieldItemSource(ComboBox cb)
        {
            if (cb == null) return;
            var items = GlobalData.GetAllItemSource();
            if (items == null || items.Count == 0) return;

            string key = cb.Name;
            var itemSource = items.ContainsKey(key) ? items[key] : null;

            cb.ItemsSource = null;
            cb.ItemsSource = itemSource;
        }

        #endregion

        #region back textbox drag event 

        private bool isDragging = false;
        private Point mouseOffset;

        private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var canvas = GetCanvas();

            if (canvas == null)
            {
                canvas = VisualTreeHelper.GetParent(this) as Canvas;
            }
            if (canvas != null)
            {
                isDragging = true;
                mouseOffset = e.GetPosition(this);
                this.CaptureMouse();
            }
        }

        private void TextBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isDragging)
            {
                this.ReleaseMouseCapture();
                isDragging = false;
            }

            //TODO update backup field to databases;
            Console.WriteLine("update backup field to databases;");
        }
        private void TextBox_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var canvas = GetCanvas();
            if (canvas != null && isDragging == true)
            {
                Point p = e.GetPosition(canvas);
                this.SetValue(Canvas.TopProperty, p.Y - mouseOffset.Y);
                this.SetValue(Canvas.LeftProperty, p.X - mouseOffset.X);
            }
        }
        private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            this.CaptureMouse();
            switch (e.Key)
            {
                case Key.Left:
                    this.SetValue(Canvas.LeftProperty, Canvas.GetLeft(this) - 1);
                    break;
                case Key.Up:
                    this.SetValue(Canvas.TopProperty, Canvas.GetTop(this) - 1);
                    break;
                case Key.Right:
                    this.SetValue(Canvas.LeftProperty, Canvas.GetLeft(this) + 1);
                    break;
                case Key.Down:
                    this.SetValue(Canvas.TopProperty, Canvas.GetTop(this) + 1);
                    break;
            }
            this.ReleaseMouseCapture();
        }
        #endregion
    }
}
